#include "NodeController/NodeControllerTask.h"
#include <QDebug>
#include <QTimer>
#include <QNetworkProxy>
#include <QEventLoop>

NodeControllerTask::NodeControllerTask(int nodeId, const QString& host, int port, QObject* parent)
    : QObject(parent), QRunnable(), nodeId(nodeId), host(host), port(port), socket(nullptr), isConnected(false)
{
    // 不在构造函数中实例化 socket
}

NodeControllerTask::~NodeControllerTask()
{
    if (socket) {
        if(isConnected){
            socket->disconnectFromHost();
            socket->waitForDisconnected(3000);  // 等待断开连接
        }
        delete socket;  // 确保 socket 被销毁
    }
}

void NodeControllerTask::run()
{
    // 在子线程的 run() 方法中实例化 socket
    socket = new QTcpSocket();  // 独立对象，不依赖父对象
    socket->setProxy(QNetworkProxy::NoProxy);  // 禁用代理

    connect(socket, &QTcpSocket::connected, this, &NodeControllerTask::onConnected, Qt::QueuedConnection);
    connect(socket, &QTcpSocket::disconnected, this, &NodeControllerTask::onDisconnected, Qt::QueuedConnection);
    connect(socket, &QTcpSocket::readyRead, this, &NodeControllerTask::onReadData, Qt::QueuedConnection);
    connect(socket, &QTcpSocket::errorOccurred, this, &NodeControllerTask::onHandleError, Qt::QueuedConnection);

    qDebug() << "Connecting to Node Controller" << nodeId << "at" << host << ":" << port;
    socket->connectToHost(host, port);
    // 设置超时回调
    QTimer::singleShot(3000, this, &NodeControllerTask::onTimeout);

    // 启动子线程的事件循环
    QEventLoop loop;
    loop.exec();  // 这将阻塞线程，直到调用 loop.quit()
}

// 槽函数，处理连接成功的事件。
void NodeControllerTask::onConnected() {
    qDebug() << "Connected to" << host << ":" << port;
    isConnected = true;  // 标记连接成功
    // 取消超时回调
    QTimer::singleShot(0, this, []() { /*qDebug() << "Connection successful, timeout cancelled.";*/ });
}

// 槽函数，处理连接断开的事件。
void NodeControllerTask::onDisconnected() {
    qDebug() << "Disconnected from" << host << ":" << port;
    delete socket;  // 确保 socket 被销毁
    QThread::currentThread()->quit();  // 退出子线程的事件循环
}

void NodeControllerTask::onReadData()
{
    if(socket->bytesAvailable() > 0){
        QByteArray data = socket->readAll();
        // qDebug() << "Node" << nodeId << "received data:" << data;
        // TODO 解析
        emit dataReady(nodeId, QString(data));  // 发送数据
    }
}

void NodeControllerTask::onHandleError(QAbstractSocket::SocketError error)
{
    qDebug() << "Node" << nodeId << "socket state:" << socket->state() << "socket error:" << error << socket->errorString();
    if (!isConnected) {
        socket->disconnectFromHost();
    }
    delete socket;  // 确保 socket 被销毁
    QThread::currentThread()->quit();  // 退出子线程的事件循环
}

void NodeControllerTask::onTimeout()
{
    if (!isConnected) {
        qDebug() << "Node" << nodeId << "timeout waiting for data";
        if (socket->state() == QAbstractSocket::ConnectedState) {
            socket->disconnectFromHost();
        }
    }
}
